<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    //
    protected  $table = 'team';

    protected $fillable = ['openid','nums','pro_id','status'];

    public function teamP()
    {
        return $this->hasMany(TeamP::class,'tm_id','id');
    }

    public function getMyTeamByProId($proId , $userId){
        $memberModel = new Member();
        $myTeam = \DB::table($this->table . ' as t')
            ->select(
                't.id' ,
                't.nums',
                't.openid',
                't.status',
                't.created_at',
                'm.nickname'
            )->leftJoin($memberModel->getTable() . ' as m' , 'm.openid' , '=' , 't.openid')
            ->where('t.pro_id' , $proId)
            ->where('m.id' , $userId)
            ->orderby('t.nums','asc')
            ->get();

        $teamPModel = new TeamP();
        $myJoinTeam = \DB::table($teamPModel->getTable() . ' as tp')
            ->select(
                't.id' ,
                't.nums',
                't.openid',
                't.status',
                't.created_at',
                'm.nickname'
            )->leftJoin($this->table . ' as t' , 't.id' , '=' , 'tp.tm_id')
            ->leftJoin($memberModel->getTable() . ' as m' , 'm.openid' , '=' , 'tp.tm_openid')
            ->where('t.pro_id' , $proId)
            ->where('m.id' , $userId)
            ->orderby('t.nums','asc')
            ->get();

        $myTeam = array_merge($myJoinTeam->toArray() , $myTeam->toArray());

        $teamIds = [];
        $i = 0;
        foreach ($myTeam as $mt){
            if(in_array($mt->id , $teamIds)){
                unset($myTeam[$i]);
            }else {
                $teamIds[] = $mt->id;
            }
            $i++;
        }

        $tmModel = new TeamP();
        $teamMember = \DB::table($tmModel->getTable() . ' as tm')
            ->leftJoin($memberModel->getTable() . ' as m' , 'm.openid' , '=' , 'tm.tm_openid')
            ->whereIn('tm_id' , $teamIds)
            ->get();

        for ($i = 0 ; $i < count($myTeam) ; $i++){
            for ($j = $i+1 ; $j < count($myTeam) ; $j++){
                if($myTeam[$i]->nums > $myTeam[$j]->nums){
                    $temp = $myTeam[$i];
                    $myTeam[$i] = $myTeam[$j];
                    $myTeam[$j] = $temp;
                }
            }
        }

        foreach ($myTeam as $mt){
            $mt->member = [];
            foreach ($teamMember as $tm){
                if($mt->id == $tm->tm_id){
                    $mt->member[] = $tm;
                }
            }
        }

        return $myTeam;
    }

}
